﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using DbControl;
using LiveCharts;
using LiveCharts.WinForms;
using LiveCharts.Wpf;
using Models;
namespace CentralMonitoring
{
    /// <summary>
    /// 趋势分析窗体
    /// </summary>
    public partial class ChartForm : Form
    {
        public string mdeviceName;
        ChartValues<double> Wdlst = new ChartValues<double>();
        ChartValues<double> Ndlst = new ChartValues<double>();        
        List<string> xTime = new List<string>();
        public ChartForm()
        {
            InitializeComponent();
        }

        private void buttonFind_Click(object sender, EventArgs e)
        {
            parameters paraIdI = this.cmbParmI.SelectedItem as parameters;
            parameters paraIdII = this.cmbParmII.SelectedItem as parameters;
            if (paraIdI == paraIdII)
            {
                MessageBox.Show("两次所选参数不能相同!","提示");
                return;
            }
            InitCharts(paraIdI, paraIdII);
        }
        private void InitCombox()
        {
            DataTable dt = OprDeviceConfig.GetDeviceBySensors();
            if (dt != null)
            {
                comboBoxDevice.DisplayMember = "device_name";
                comboBoxDevice.ValueMember = "device_code";
                comboBoxDevice.DataSource = dt;
                comboBoxDevice.SelectedIndex = 0;
            }            
            if (comboBoxDevice.Items.Count > 0)
            {
                if (!string.IsNullOrEmpty(mdeviceName))
                {
                    comboBoxDevice.Text = mdeviceName;
                }
                else
                {
                    comboBoxDevice.SelectedIndex = 0;
                }
            }            

            List<parameters> list = OprParameter.GetParameterAll();
            List<parameters> list2 = OprParameter.GetParameterAll();
            if (list != null && list.Count > 0)
            {
                cmbParmI.DisplayMember = "parameter_name";
                cmbParmI.ValueMember = "parameter_code";
                cmbParmI.DataSource = list;
                cmbParmII.DisplayMember = "parameter_name";
                cmbParmII.ValueMember = "parameter_code";
                cmbParmII.DataSource = list2;
            }
            cmbParmI.SelectedIndex = 0;
            cmbParmII.SelectedIndex = 1;

            parameters paraIdI = this.cmbParmI.SelectedItem as parameters;
            parameters paraIdII = this.cmbParmII.SelectedItem as parameters;
            InitCharts(paraIdI, paraIdII);
        }
        private void ChartForm_Load(object sender, EventArgs e)
        {
            dateTimePicker开始时间.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            dateTimePicker终止时间.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));            
            this.StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            this.WindowState = FormWindowState.Maximized;
            InitCombox();
        }
        private void InitList()
        {
            try
            {               
                DataTable dt = DbHelper.SelectForPrint(dateTimePicker开始时间.Value, dateTimePicker终止时间.Value);
                if (dt != null)
                {
                    xTime.Clear();
                    Wdlst.Clear();
                    Ndlst.Clear();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            double dmtmp =0;
                            xTime.Add(dt.Rows[i][1].ToString());
                            if (!string.IsNullOrEmpty(dt.Rows[i][2].ToString()))
                                dmtmp = double.Parse(dt.Rows[i][2].ToString());
                            else
                                dmtmp = 0;
                            Wdlst.Add(dmtmp);
                            if (!string.IsNullOrEmpty(dt.Rows[i][3].ToString()))
                                dmtmp = double.Parse(dt.Rows[i][3].ToString());
                            else
                                dmtmp = 0;
                            Ndlst.Add(dmtmp);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 60; i++)
                        {
                            DateTime time = this.dateTimePicker终止时间.Value.AddMinutes(-60);
                            Wdlst.Add(0);
                            xTime.Add(time.ToString());
                            Ndlst.Add(0);
                        }
                    }
                }
               
            }
            catch (Exception ex)
            {
                lLogWrite.WriteLog(ex.ToString());
            }
        }
        private void InitCharts(parameters ParaI,parameters ParaII)
        {
            string filter = "";
            if (!string.IsNullOrEmpty(comboBoxDevice.Text))
            {
                filter = comboBoxDevice.SelectedValue.ToString();
            }

            string strParaI = ParaI.parameter_code;
            string strParaII = ParaII.parameter_code; 
            try
            {
                DataTable dt =OprUI.GetSensorDatasByDeviceCodeAndPara(dateTimePicker开始时间.Value,dateTimePicker终止时间.Value,filter,strParaI,strParaII);
                if (dt != null)
                {
                    xTime.Clear();
                    Wdlst.Clear();
                    Ndlst.Clear();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            double dmtmp = 0;
                            xTime.Add(dt.Rows[i][1].ToString());
                            if (!string.IsNullOrEmpty(dt.Rows[i][2].ToString()))
                                dmtmp = double.Parse(dt.Rows[i][2].ToString());
                            else
                                dmtmp = 0;
                            Wdlst.Add(dmtmp);
                            if (!string.IsNullOrEmpty(dt.Rows[i][3].ToString()))
                                dmtmp = double.Parse(dt.Rows[i][3].ToString());
                            else
                                dmtmp = 0;
                            Ndlst.Add(dmtmp);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < 60; i++)
                        {
                            DateTime time = this.dateTimePicker终止时间.Value.AddMinutes(i-60);
                            Wdlst.Add(0);                            
                            Ndlst.Add(0);
                            xTime.Add(time.ToString());
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                lLogWrite.WriteLog(ex.ToString());
            }
            string ParaIMc = cmbParmI.Text;
            string ParaIIMc = cmbParmII.Text;
            ReLoadChart(ParaIMc,ParaIIMc);
        }
        private string GetPara(int index)
        {
            string s = "";
            switch (index)
            {
                case 0:
                    s = "temper";
                    break;
                case 1:
                    s = "vis";
                    break;
                case 2:
                    s = "vis40";
                    break;
                case 3:
                    s = "dens";
                    break;
                case 4:
                    s = "diel";
                    break;
                case 5:
                    s = "ppm";
                    break;
                case 6:
                    s = "fe1";
                    break;
                case 7:
                    s = "fe2";
                    break;
                case 8:
                    s = "fe3";
                    break;
                case 9:
                    s = "fe4";
                    break;
                case 10:
                    s = "fe5";
                    break;
                case 11:
                    s = "fe6";
                    break;
                case 12:
                    s = "fe7";
                    break;
                case 13:
                    s = "fe8";
                    break;
                case 14:
                    s = "fe9";
                    break;
                case 15:
                    s = "fe10";
                    break;
                case 16:
                    s = "nfe1";
                    break;
                case 17:
                    s = "nfe2";
                    break;
                case 18:
                    s = "nfe3";
                    break;
                case 19:
                    s = "nfe4";
                    break;    
                case 20:
                    s = "class6";
                    break;
                case 21:
                    s = "class_total";
                    break;
            }
            return s;
        }
        private void ReLoadChart(string NameI, string NameII)
        {
            cartesianChart1.DisableAnimations = true;
            cartesianChart1.Series.Clear();
            cartesianChart1.AxisY.Clear();
            cartesianChart1.AxisX.Clear();
            cartesianChart1.Series.Add(new LineSeries
            {
                Values = Wdlst,
                //DataLabels = true,
                Title =NameI,
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
                ScalesYAt = 0
            });
            cartesianChart1.Series.Add(new LineSeries
            {
                Values =Ndlst,              
                Title = NameII,
                LineSmoothness = 1,
                LabelPoint = (point => point.Y.ToString()),
                ScalesYAt = 1
            });

            cartesianChart1.AxisY.Add(new Axis
            {
                Foreground = System.Windows.Media.Brushes.DodgerBlue,
                Title = NameI,
                MinValue = 0
            });
            cartesianChart1.AxisY.Add(new Axis
            {
                Foreground = System.Windows.Media.Brushes.IndianRed,
                Title = NameII,
                MinValue=0,
                Position = AxisPosition.RightTop,
               

            });
            cartesianChart1.AxisX.Add(new Axis
            {               
                Labels = xTime,
                LabelsRotation = 15,
                Separator = new Separator { Step = 3 }
            });

        }
        private void RefreshChart(string NameI,string NameII)
        {
            cartesianChart1.Series.Clear();
            cartesianChart1.AxisY.Clear();
            cartesianChart1.AxisX.Clear();
            List<string> title_names = new List<string>();
            title_names.Add(NameI);
            title_names.Add(NameII);            
            LiveCharts.SeriesCollection seriesViews = new SeriesCollection();
            List<ChartValues<double>> _values = new List<ChartValues<double>>();
            _values.Add(Wdlst);
            _values.Add(Ndlst); 
            for (int i = 0; i < title_names.Count; i++)
            {
                LineSeries lineseries = new LineSeries();
                lineseries.DataLabels = true;
                lineseries.Title = title_names[i];
                lineseries.Values = _values[i];
                lineseries.LineSmoothness = 1;
                lineseries.LabelPoint = (point => point.Y.ToString() );               
                seriesViews.Add(lineseries);              
                Axis axis;
                if (i > 0)
                {
                     axis= new Axis
                    {
                        Title = title_names[i],
                        //Labels = xTime,
                        //MinValue = 0,
                        Foreground = System.Windows.Media.Brushes.Blue,
                        Position=AxisPosition.RightTop
                    };
                }
                else
                {
                     axis = new Axis
                    {
                        Title = title_names[i],
                        //Labels = xTime,
                        //MinValue = 0,
                        Foreground = System.Windows.Media.Brushes.Blue
                    };
                }
                cartesianChart1.AxisY.Add(axis);

            }
            cartesianChart1.Series = seriesViews;

            cartesianChart1.AxisX.Add(new Axis
            {
                Title = "监测值",
                Labels = xTime,
            });
           
            //cartesianChart1.AxisY.Add(new Axis
            //{
            //    Title = "监测值",
            //    LabelFormatter = value => value.ToString()
            //});
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Title = "保存为图片文件";
                dlg.Filter = "jpg图片(*.JPG)|*.JPEG|png图片(*.PNG)|*.PNG|jpeg图片(*.JPEG)|*.JPEG";
                dlg.FilterIndex = 1;
                dlg.RestoreDirectory = true;
                dlg.CreatePrompt = true;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    using (var bmp = new Bitmap(cartesianChart1.Width, cartesianChart1.Height))
                    {
                        cartesianChart1.DrawToBitmap(bmp, new Rectangle(0, 0, cartesianChart1.Width, cartesianChart1.Height));
                        bmp.Save(dlg.FileName);
                        MessageBox.Show(this, "保存图片成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据导出失败:" + ex.Message.ToString());
            }
        }
    }
}
